package com.kingdee.pda.plugins.http.serverinterface.impl;

import android.content.Context;
import android.text.TextUtils;

import com.example.basecommon.http.MyObserver;
import com.example.basecommon.http.RxHelper;
import com.example.basecommon.http.rxjava.BaseResponse;
import com.example.basecommon.http.rxjava.HttpUtils;
import com.example.basecommon.utils.Account;
import com.google.gson.Gson;
import com.kingdee.pda.Api;
import com.kingdee.pda.entity.Warehouse;
import com.example.basecommon.utils.LoginUtil;
import com.kingdee.pda.plugins.http.common.KeyConstants;
import com.kingdee.pda.plugins.http.common.OnRequestCallback;
import com.kingdee.pda.plugins.http.serverinterface.IWarehouse;
import com.kingdee.pda.util.CommonUtil;
import com.example.basecommon.utils.ConstantUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.OkHttpRequestBuilder;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 仓库接口相关实现
 * Created by zhanlg
 * DATE 2021/5/24
 * TIME 15:05
 */
public class WarehouseImpl implements IWarehouse {
    /**
     * 查询当前仓库
     **/
    private static final String API_QUERY_CURRENT_WAREHOUSE = "/kapi/app/oewms/query_current_warehouse_pda";
    /**
     * 设置选中仓库
     **/
    private static final String API_SAVE_WAREHOUSE = "/kapi/app/oewms/save_pda_warehouse";

    @Override
    public void queryWarehouseList(Context context, boolean isInit, final OnRequestCallback<List<Warehouse>> callback) {

        HashMap<String, Object> map = new HashMap<>();
        map.put("isInit", isInit);
        map.put("userId", Account.INSTANCE.getAccountName());
        map.put("requestFrom","1");
        MyObserver<List<Warehouse>> myObserver = new MyObserver<List<Warehouse>>(context) {
            @Override
            public void onSuccess(BaseResponse<List<Warehouse>> result) {
                callback.onSuccessCallback(result.data, "");
            }

            @Override
            public void onFailure(BaseResponse result, String msg) {
                callback.onFailedCallback(false, msg);

            }
        };
        HttpUtils.request(Api.class)
                .getWarehouseList(ConstantUtil.GET_WAREHOUSE_LIST, map)
                .compose(RxHelper.observableIO2Main(context))
                .subscribe(myObserver);

    }

    private JSONObject setQueryWarehouseListParamValue(boolean isInit) {
        JSONObject json = new JSONObject();
        try {
            json.put("isInit", isInit);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

    @Override
    public void queryCurrentWarehouse(final OnRequestCallback<Warehouse> callback) {
        String apiUrl = ConstantUtil.getServerUrl() + API_QUERY_CURRENT_WAREHOUSE;

        Request request = new Request.Builder()
                .addHeader("accessToken", LoginUtil.getToken())
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .url(apiUrl)
                .get()
                .build();
        OkHttpUtils.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                callback.onFailedCallback(false, CommonUtil.getErrorMsg(e.getMessage(), "请求失败！"));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    String result = response.body().string();
                    if (!TextUtils.isEmpty(result) && result.contains(KeyConstants.Response.SUCCESS)) {
                        JSONObject resultJson;
                        try {
                            resultJson = new JSONObject(result);
                            boolean isSuccess = resultJson.optBoolean(KeyConstants.Response.SUCCESS, false);
                            if (isSuccess) {
                                JSONObject data = resultJson.getJSONObject(KeyConstants.Response.DATA);
                                if (data != null) {
                                    Warehouse warehouse = new Gson().fromJson(data.toString(), Warehouse.class);
                                    callback.onSuccessCallback(warehouse, "");
                                } else {
                                    callback.onFailedCallback(false, "绑定仓库信息为空");
                                }
                            } else {
                                callback.onFailedCallback(false,
                                        CommonUtil.getErrorMsg(resultJson.optString(KeyConstants.Response.MESSAGE), "请求失败！"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            callback.onFailedCallback(false, CommonUtil.getErrorMsg(response.message(), "数据解析失败！"));
                        }
                    } else {
                        callback.onFailedCallback(true, CommonUtil.getErrorMsg(response.message(), "请求失败！"));
                    }
                } else {
                    callback.onFailedCallback(false, response.message());
                }
            }
        });
    }

    @Override
    public void saveWarehouse(long warehouseId, final OnRequestCallback<Warehouse> callback) {
        String apiUrl = ConstantUtil.getServerUrl() + API_SAVE_WAREHOUSE;
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"),
                setSaveWarehouseParamValue(warehouseId).toString());

        Request request = new Request.Builder()
                .addHeader("accessToken", LoginUtil.getToken())
                .url(apiUrl)
                .post(requestBody)
                .build();
        OkHttpUtils.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                callback.onFailedCallback(false, CommonUtil.getErrorMsg(e.getMessage(), "请求失败！"));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    String result = response.body().string();
                    if (!TextUtils.isEmpty(result) && result.contains(KeyConstants.Response.SUCCESS)) {
                        JSONObject resultJson;
                        try {
                            resultJson = new JSONObject(result);
                            boolean isSuccess = resultJson.optBoolean(KeyConstants.Response.SUCCESS, false);
                            if (isSuccess) {
                                callback.onSuccessCallback(null, true);
                            } else {
                                callback.onFailedCallback(false,
                                        CommonUtil.getErrorMsg(resultJson.optString(KeyConstants.Response.MESSAGE), "请求失败！"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            callback.onFailedCallback(false, CommonUtil.getErrorMsg(response.message(), "数据解析失败！"));
                        }
                    } else {
                        callback.onFailedCallback(true, CommonUtil.getErrorMsg(response.message(), "请求失败！"));
                    }
                } else {
                    callback.onFailedCallback(false, response.message());
                }
            }
        });
    }

    private JSONObject setSaveWarehouseParamValue(long warehouseId) {
        JSONObject json = new JSONObject();
        try {
            json.put("warehouseId", warehouseId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }
}
